package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.UserRepository;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService implements UserDetailsService {
    private final UserRepository userRepository;
    private final JwtUtils jwtUtils;
    private final BCryptPasswordEncoder passwordEncoder;
    
    public String login(String username, String password) {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        log.debug("用户登录: username={}, 输入密码={}, 数据库密码={}", 
            username, password, user.getPassword());
            
        // 尝试直接匹配密码
        if (passwordEncoder.matches(password, user.getPassword())) {
            user.setLastLoginTime(LocalDateTime.now());
            userRepository.save(user);
            return jwtUtils.generateToken(username);
        }
        
        // 如果密码不匹配，尝试直接比较（用于处理旧密码）
        if (password.equals(user.getPassword())) {
            // 更新为新的加密方式
            user.setPassword(passwordEncoder.encode(password));
            user.setLastLoginTime(LocalDateTime.now());
            userRepository.save(user);
            log.info("用户密码已升级到新的加密方式: username={}", username);
            return jwtUtils.generateToken(username);
        }
        
        log.debug("密码不匹配: username={}, 输入密码={}, 数据库密码={}", 
            username, password, user.getPassword());
        throw new RuntimeException("密码错误");
    }
    
    public void register(String username, String password) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        String encodedPassword = passwordEncoder.encode(password);
        log.debug("用户注册: username={}, 原始密码={}, 加密后密码={}", 
            username, password, encodedPassword);
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(encodedPassword);
        user.setRole("user");
        
        userRepository.save(user);
    }
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole().toUpperCase()))
        );
    }
} 